﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iS3.DAL
{
    /// <summary>
    /// 数据库操作基类 （模板模式：Template Method）
    /// 属性管理
    /// </summary>
    public abstract class iS3DalBase : IDisposable
    {
        protected DbProviderFactory _fac = null;
        protected DbConnection _con = null;
        protected DbCommand _com;
        public virtual char Pre
        {
            get
            {
                return '@';
            }
        }
        public DbConnection Con
        {
            get
            {
                return _con;
            }
        }
        public DbCommand Com
        {
            get
            {
                return _com;
            }
        }
        public virtual bool AddParameters(string parameterName, object value, DbType dbType, int size, ParameterDirection direction)
        {
            parameterName = parameterName.Substring(0, 1) == Pre.ToString() ? parameterName : Pre + parameterName;
            if (Com == null)
            {
                return false;
            }
            if (Com.Parameters.Contains(parameterName))//已经存在，不添加
            {
                return false;
            }
            DbParameter para = _com.CreateParameter();
            para.ParameterName = parameterName;
            para.Value = value == null ? DBNull.Value : value;
            if (dbType == DbType.Time)// && dalType != DalType.MySql
            {
                para.DbType = DbType.String;
            }
            else
            {
                if (dbType == DbType.DateTime && value != null)
                {
                    string time = Convert.ToString(value);
                    if (time == DateTime.MinValue.ToString())
                    {
                        para.Value = SqlDateTime.MinValue;
                    }
                    para.DbType = dbType;
                }
                if (dbType != DbType.Binary && size > -1)
                {
                    if (size != para.Size)
                    {
                        para.Size = size;
                    }
                }
                para.Direction = direction;
                if (para.DbType == DbType.String && para.Value != null)
                {
                    para.Value = Convert.ToString(para.Value);
                }
                Com.Parameters.Add(para);

            }
            return true;
        }
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
